from common.json_util import to_dicts, to_dict, to_json
from daos.system_log_dao import query_system_log_with_page, add_system_log
from daos.system_user_dao import query_system_user
from models.biz_enum import SystemLogModule
from models.system_log import SystemLog
from rules import PAGINATION_PAGE_SIZE, db_commit


def search_system_log_with_page(page_index, data_param):
    data_param['page'] = page_index
    data_param['page_size'] = PAGINATION_PAGE_SIZE
    result = query_system_log_with_page(data_param)
    item_dicts = to_dicts(result.items)
    for item in item_dicts:
        item["module_name"] = SystemLogModule.get_name(item.get("module"))

        if item.get("operator"):
            user_orm = query_system_user(item.get("operator"))
            if user_orm:
                user_dict = to_dict(user_orm)
                item["operator_name"] = user_dict.get("real_name")

    result.items = item_dicts
    return result


def create_system_log(log_dict, is_commit=False):
    log_orm = SystemLog()

    log_orm.module = log_dict["module"]
    log_orm.operation_detail = to_json(log_dict["operation_detail"])
    log_orm.operator = log_dict["operator"]

    result = add_system_log(log_orm, is_commit)

    if not is_commit:
        db_commit()

    return result.to_dict()
